package org.concepts.java.antlr.csv;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.junit.Test;


public class TestCSVParser {


  @Test
  public void testParserOneRecord() throws RecognitionException {
    processInputUsingCSVParser("1,2,3");
  }

  @Test
  public void testParserThreeRecord() throws RecognitionException {
    processInputUsingCSVParser("1,2,3\n10,11,12\r\n100,101,102");
  }

  @Test
  public void testParserFileWithComments() throws RecognitionException {
    processInputUsingCSVParser("1,2,3\n//Next row below comment\n10,11,12\n" +
        "/* Multi line \n comment*/100,101,102\n");
  }
  
  @Test
  public void testParserDefaultRecognitionTolerance() throws RecognitionException {
    processInputUsingCSVParser("1, 2,\t 3\n10,11,12,a\n100,101,102");
  }
  
  @Test
  public void testParserMissingSeparator() throws RecognitionException {
    processInputUsingCSVParser("1,2,3 4\n10,11,12\n");
  }

  @Test
  public void testParserExtraSeparator() throws RecognitionException {
    processInputUsingCSVParser(",1,2,3,4\n10,11,12");
  }

  /**
   * Process the input using {@link CSVParser}
   * 
   * @param input
   *          input. Cannot be null.
   * @throws RecognitionException
   *           Thrown if tokens don't follow the rule
   */
  private void processInputUsingCSVParser(String input)
      throws RecognitionException {
    CSVParser csvParser = getCSVParser(input);
    csvParser.file();
    System.out.println("Number of rows: " + csvParser.getRecordCount());
  }

  /**
   * Returns an instance of CSV parser for the input
   * 
   * @param input
   *          input. Cannot be null.
   * @return csv parser. Is never null.
   */
  private CSVParser getCSVParser(String input) {
    System.out.println("\n\nInput [" + input + "]");
    CSVLexer csvLexer = new CSVLexer(new ANTLRStringStream(input));
    CSVParser csvParser = new CSVParser(new CommonTokenStream(csvLexer));
    return csvParser;
  }

  
}
